<template>
  <el-card class="box-card">
    <el-button type="primary" :icon="Plus" @click="handleTrademark('add', {})">
      添加品牌
    </el-button>
    <el-table :data="trademarkArr" border height="400" style="margin: 10px 0px">
      <el-table-column prop="id" label="序号" width="60" />
      <el-table-column prop="tmName" label="品牌名称" width="180" />
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <template #="{ row }">
          <el-image style="width: 100px; height: 100px" :src="row.logoUrl" />
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        align="center"
        label="品牌操作"
        width="200"
      >
        <template #="{ row }">
          <el-button
            type="primary"
            :icon="Edit"
            size="small"
            @click="handleTrademark('edit', row)"
          />
          <el-button
            type="primary"
            :icon="Delete"
            size="small"
            @click="deleteTrademark(row.id)"
          />
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :pager-count="9"
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      background
      :page-sizes="[3, 5, 7, 9]"
      layout="prev, pager, next, jumper, sizes, total"
      :total="total"
      @size-change="sizeChange"
      @current-change="getHasTrademark"
    />
  </el-card>
  <el-dialog
    v-model="dialogFormVisible"
    :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
  >
    <el-form :model="trademarkParams" :rules="rules" ref="formRef">
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input v-model="trademarkParams.tmName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkParams.logoUrl"
            :src="trademarkParams.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAddOrUpdateTrademark">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
// 引入组合式API函数ref
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, UploadProps } from 'element-plus'
// 引入接口
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import type {
  Records,
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/trademark/type'

//获取el-form组件实例
const formRef = ref()
// 当前页码
const pageNo = ref<number>(1)
// 每一页展示多少条数据
const limit = ref<number>(3)
// 存储已有品牌数据总数
const total = ref<number>(0)
// 存储已有品牌的数据
const trademarkArr = ref<Records>([])
// 控制对话框显示与隐藏
const dialogFormVisible = ref<boolean>(false)
// 定义收集新增品牌数据
const trademarkParams = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
})

// 图片上传成功钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  // response:即为当前这次上传图片post请求服务器返回的数据
  // 收集上传图片的地址,添加一个新的品牌的时候带给服务器
  trademarkParams.logoUrl = response.data
}

// 上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
  // 要求:上传文件格式png|jpg|gif 4M
  if (['image/png', 'image/jpeg', 'image/gif'].includes(rawFile.type)) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传文件大小小于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件格式务必PNG|JPG|GIF',
    })
    return false
  }
}

// 品牌名称校验器
const validatorTmName = (rule: any, value: string, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    // 校验未通过返回的错误的提示信息
    callBack(new Error('品牌名称位数需大于或等于两位'))
  }
}
// 品牌LOGO校验器
const validatorLogoUrl = (rule: any, value: string, callBack: any) => {
  // 如果图片上传
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}
// 表单校验规则对象
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
}

// 获取已有品牌的接口封装为一个函数:在任何情况下向获取数据,调用次函数即可
const getHasTrademark = async (pager = 1) => {
  // 当前页码
  pageNo.value = pager
  const result: TradeMarkResponseData = await reqHasTrademark(
    pageNo.value,
    limit.value,
  )
  if (result.code == 200) {
    // 存储已有品牌总个数
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}

const sizeChange = () => {
  // 当前每一页的数据量发生变化的时候，当前页码归1
  getHasTrademark()
}

// 添加品牌按钮的回调
const handleTrademark = (_type: string, _rowData: object) => {
  // 对话框显示
  dialogFormVisible.value = true

  switch (_type) {
    case 'add':
      formRef.value.resetFields()
      return
    case 'edit':
      Object.assign(trademarkParams, _rowData)
      return
    default:
      break
  }
}

const handleAddOrUpdateTrademark = async () => {
  await formRef.value.validate()
  const result: any = await reqAddOrUpdateTrademark(trademarkParams)
  // 添加|修改已有品牌
  if (result.code == 200) {
    // 关闭对话框
    dialogFormVisible.value = false
    // 弹出提示信息
    ElMessage({
      type: 'success',
      message: trademarkParams.id ? '修改品牌成功' : '添加品牌成功',
    })
    //再次发请求获取已有全部的品牌数据
    getHasTrademark(trademarkParams.id ? pageNo.value : 1)
  } else {
    // 添加品牌失败
    ElMessage({
      type: 'error',
      message: trademarkParams.id ? '修改品牌失败' : '添加品牌失败',
    })
    // 关闭对话框
    dialogFormVisible.value = false
  }
}

//气泡确认框确定按钮的回调
const deleteTrademark = async (id: number) => {
  //点击确定按钮删除已有品牌请求
  const result = await reqDeleteTrademark(id)
  if (result.code == 200) {
    //删除成功提示信息
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    //再次获取已有的品牌数据
    getHasTrademark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除品牌失败',
    })
  }
}

// 组件挂载完毕钩子---发一次请求,获取第一页、一页三个已有品牌数据
onMounted(() => getHasTrademark())
</script>

<style scoped lang="scss">
.avatar-uploader {
  display: flex;
  justify-content: center;
  width: 178px;
  height: 178px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;

  .avatar-image {
    display: block;
  }

  .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
}
</style>
